#!/usr/bin/env python3
"""
简化的测试运行脚本

提供快速运行测试的便捷脚本。
"""

import os
import sys
import argparse
import subprocess
from pathlib import Path


def run_command(cmd, description):
    """运行命令并处理结果"""
    print(f"\n{'='*60}")
    print(f"🚀 {description}")
    print(f"{'='*60}")

    try:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)

        if result.stdout:
            print("📤 输出:")
            print(result.stdout)

        if result.stderr:
            print("⚠️  错误:")
            print(result.stderr)

        if result.returncode == 0:
            print(f"✅ {description} - 成功")
        else:
            print(f"❌ {description} - 失败 (退出码: {result.returncode})")

        return result.returncode == 0

    except Exception as e:
        print(f"💥 {description} - 异常: {e}")
        return False


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="OpenHarmony 前端测试运行器")
    parser.add_argument(
        "test_type",
        choices=["all", "unit", "integration", "e2e", "smoke", "lint"],
        default="all",
        nargs="?",
        help="要运行的测试类型"
    )
    parser.add_argument(
        "--verbose", "-v",
        action="store_true",
        help="详细输出"
    )
    parser.add_argument(
        "--skip-env-check",
        action="store_true",
        help="跳过环境检查"
    )

    args = parser.parse_args()

    # 确保在正确的目录
    script_dir = Path(__file__).parent
    os.chdir(script_dir)

    # 检查 Python 环境
    print("🔍 检查 Python 环境...")
    try:
        import pytest
        print(f"✅ pytest 版本: {pytest.__version__}")
    except ImportError:
        print("❌ pytest 未安装，请运行: pip install -r requirements.txt")
        sys.exit(1)

    success = True

    if args.test_type in ["all", "smoke"] and not args.skip_env_check:
        # 环境检查
        print("\n🔍 检查测试环境...")

        # 检查后端服务
        try:
            import requests
            response = requests.get("http://localhost:9999/docs", timeout=5)
            if response.status_code == 200:
                print("✅ 后端服务运行正常")
            else:
                print("⚠️  后端服务状态异常")
        except:
            print("❌ 后端服务不可用 (localhost:9999)")
            print("💡 请启动后端服务: cd ../analyser && python main.py")

        # 检查前端服务
        try:
            response = requests.get("http://localhost:3001", timeout=5)
            if response.status_code == 200:
                print("✅ 前端服务运行正常")
            else:
                print("⚠️  前端服务状态异常")
        except:
            print("❌ 前端服务不可用 (localhost:3001)")
            print("💡 请启动前端服务: npm run dev")

    # 运行不同类型的测试
    if args.test_type in ["all", "unit"]:
        success &= run_command(
            "python -m pytest unit/ -v" + (" --tb=short" if not args.verbose else " --tb=long"),
            "单元测试"
        )

    if args.test_type in ["all", "integration"]:
        success &= run_command(
            "python -m pytest integration/ -v" + (" --tb=short" if not args.verbose else " --tb=long"),
            "集成测试"
        )

    if args.test_type in ["all", "e2e"]:
        print("\n⚠️  E2E 测试需要 WebDriver 和图形界面")
        e2e_cmd = "python -m pytest e2e/ -v" + (" --tb=short" if not args.verbose else " --tb=long")
        if args.skip_env_check:
            e2e_cmd += " --skip-env-check"
        success &= run_command(e2e_cmd, "端到端测试")

    if args.test_type == "smoke":
        # 运行冒烟测试
        success &= run_command(
            "python test_comprehensive.py --type smoke",
            "冒烟测试"
        )

    if args.test_type == "lint":
        # 运行代码检查
        os.chdir(script_dir.parent)
        success &= run_command(
            "npm run lint",
            "代码格式检查"
        )

    # 总结
    print(f"\n{'='*60}")
    if success:
        print("🎉 所有测试通过！")
        sys.exit(0)
    else:
        print("❌ 部分测试失败")
        sys.exit(1)


if __name__ == "__main__":
    main()